import cache from './cache';
import store from './store';
export default {
  socket: null,
  init() {
    const user = cache.fetchUser();
    if (user) {
      const host = `121.199.12.118:8080`;
      this.socket = new WebSocket(`ws://${host}/protal/websocket/${user.username}`);
      this.socket.onopen = this.onOpen;
      this.socket.onmessage = this.onMessage;
      this.socket.onclose = this.onClose;
    }
  },

  onOpen() {
    console.log('socket onopen');
  },

  onMessage(evt) {
    if (evt.data) {
      const data = JSON.parse(evt.data);
      console.log(data);
      const msgType = data.messageType;
      const unreadCount = data.unreadCount;
      if (msgType === 4) { // 新消息来了

      }
      console.log('未读消息数量', unreadCount);
      if (store.state.unreadNum !== unreadCount) {
        store.commit('unread', unreadCount);
      }
    }
  },

  onClose() {
    console.log('on close');
  },

  send({
    msg,
    to
  }) {
    const user = cache.fetchUser();
    const message = {
      message: msg,
      username: user.username,
      to: to
    };
    this.socket.send(JSON.stringify(message));
  }
};
